﻿/*********************************************************

    Copyright (c) Microsoft. All rights reserved.
    This code is licensed under the Microsoft Public License.
    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.

*********************************************************/
using System;
using System.Windows;
using System.Windows.Controls;
using OData.Silverlight;

namespace SL_OData_Explorer
{
    public class ODataNavigationPropertyColumn : DataGridBoundColumn
    {
        public Action<ODataEntity, NavigationProperty> OnEntitySelected { get; set; }
        public NavigationProperty Association { get; set; }
        protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
        {
            return new TextBlock() { Text = " " };
        }

        protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
        {
            ODataEntity entity = dataItem as ODataEntity;
            HyperlinkButton clickHereButton = new HyperlinkButton();
            clickHereButton.Click += new RoutedEventHandler(clickHereButton_Click);
            string strKeyString = "";
            foreach (string keyProperty in entity.EntityType.KeyProperties)
            {
                if (strKeyString.Length > 0)
                {
                    strKeyString += "&";
                }
                strKeyString += String.Format("{0}={1}", keyProperty, entity[keyProperty]);
            }
            clickHereButton.Style = Application.Current.Resources["ODataNavigationLink"] as Style;
            clickHereButton.Content = Association.Name;
            clickHereButton.SetBinding(HyperlinkButton.TagProperty, this.Binding);

            return clickHereButton;
        }

        void clickHereButton_Click(object sender, RoutedEventArgs e)
        {
            HyperlinkButton buttonClicked = sender as HyperlinkButton;
            if (buttonClicked != null && buttonClicked.Tag != null)
            {
                OnEntitySelected(buttonClicked.Tag as ODataEntity, Association);
            }
        }

        protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs)
        {
            throw new NotImplementedException();
        }
    }
}
